package main

import (
	"fmt"
	"go-xorm-01/utils"
	"time"
	"xorm.io/xorm"
	"xorm.io/xorm/log"
	"xorm.io/xorm/names"
)

var engine *xorm.Engine

// 删除数据 : https://xorm.io/zh/docs/chapter-07/readme/
// 删除数据用 Delete方法，参数为struct的指针并且成为查询条件。
func main() {
	SnakeMapper()
	insetManyUser(engine)
	engine.DumpAllToFile("demo07-delete/demo01-delete/sql.sql")
	//deleteUser(engine)

}

func deleteUser(engine *xorm.Engine) {
	var user UserDelete
	de, _ := engine.ID(1).Delete(user)
	fmt.Println(de)

	//如果你真的希望将整个表删除，你可以
	//engine.Where("1=1").Delete(new(UserDelete))
}

func SnakeMapper() {
	engine = utils.GenerateEngine()
	engine.SetMapper(names.SnakeMapper{}) // SnakeMapper 【默认】
	err := engine.Sync2(new(UserDelete))
	if err != nil {
		fmt.Printf("err:%v", err)
	}
	engine.ShowSQL(true)
	engine.SetLogLevel(log.LOG_DEBUG)

}

func insetManyUser(engine *xorm.Engine) {
	groupOne := make([]*UserDelete, 0)
	for i := 0; i < 5; i++ {
		groupOne = append(groupOne, &UserDelete{
			Username: fmt.Sprintf("zhangsan-%d", i),
			Password: fmt.Sprintf("123456-%d", i),
			GroupId:  1,
			Rank:     i,
		})
	}
	engine.Insert(groupOne)

	groupTwo := make([]*UserDelete, 0)
	for i := 0; i < 3; i++ {
		groupTwo = append(groupTwo, &UserDelete{
			Username: fmt.Sprintf("lisi-%d", i),
			Password: fmt.Sprintf("00000-%d", i),
			GroupId:  2,
			Rank:     i,
		})
	}
	engine.Insert(groupTwo)

}

type JsonTime time.Time

func (j JsonTime) MarshalJSON() ([]byte, error) {
	return []byte(`"` + time.Time(j).Format("2006-01-02 15:04:05") + `"`), nil
}

type UserDelete struct {
	Id        int64     `xorm:"pk autoincr"`                                              //指定列名 ，默认id
	Username  string    `xorm:"varchar(25) notnull unique(u_p) 'username' comment('姓名')"` //复合唯一索引
	Password  string    `xorm:"varchar(25) notnull unique(u_p) 'password' comment('密码')"` //复合唯一索引
	TimeOne   time.Time `xorm:"created"`
	TimeTwo   JsonTime  `xorm:"created"`
	TimeThree int64     `xorm:"created"`
	GroupId   int64
	Rank      int
	Version   int       `xorm:"version"`
	UpdatedAt time.Time `xorm:"updated"`
}
